package com.finals.finalsscreen;

import android.app.Instrumentation;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.finals.finalsscreen.util.Util;

/**
 * Type int 0开启 1接听电话 2结束进程
 * 
 * @author liufeilong
 * 
 */
public class AcceptCallActivity extends BaseActivity implements OnClickListener {

	View acceptView;

	View denyView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dialog);
		InitView();
		InitWindow();
		InitData();
	}

	private void InitView() {
		acceptView = findViewById(R.id.accept);
		acceptView.setOnClickListener(this);

		denyView = findViewById(R.id.deny);
		denyView.setOnClickListener(this);
	}

	private void InitData() {
		InitIntent(getIntent());
	}

	@Override
	protected void onNewIntent(Intent intent) {
		InitIntent(intent);
		super.onNewIntent(intent);
	}

	private void InitIntent(Intent intent) {
		int Type = intent.getIntExtra("Type", -1);
		switch (Type) {
		case 0:
			// 开启
			break;
		case 1:
			AcceptCall();
			break;
		case 2:
			this.finish();
			break;
		default:
			moveTaskToBack(true);
			break;
		}
	}

	private void InitWindow() {
		Window mWindow = getWindow();
		mWindow.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
	}

	@Override
	public void onClick(View view) {
		if (view.equals(acceptView)) {
			AcceptCall();
		} else if (view.equals(denyView)) {
			DenyCall();
		}
	}

	private void AcceptCall() {
		new Thread(mRunnable).start();
	}

	Runnable mRunnable = new Runnable() {

		@Override
		public void run() {
			Instrumentation instrumentation = new Instrumentation();
			try {
				instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_HEADSETHOOK);
			} catch (Exception e) {
				e.printStackTrace();
				mHandler.sendEmptyMessage(1);
			}
		}
	};

	private void DenyCall() {
		Util.endPhone(this);
	}

	Handler mHandler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				Toast.makeText(AcceptCallActivity.this, "接听电话失败", Toast.LENGTH_SHORT).show();
				break;
			case 1:
				moveTaskToBack(true);
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onDestroy() {
		mHandler.removeCallbacksAndMessages(null);
		super.onDestroy();
		overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
		android.os.Process.killProcess(android.os.Process.myPid());
	}
}
